package com.xtoneict;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.symmetric.SM4;
import com.xtoneict.framework.util.CallBack;
import com.xtoneict.framework.util.json.JsonUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URI;
import java.util.*;

/**
 * <pre>
 * @TODO 描述文件用途
 * </pre>
 *
 * @author jew
 * @date 2024/3/13 10:47
 * @company 成都信通信息技术有限公司
 */
public class TestWs {

    private static WebSocketClient client = null;
    private static boolean open = false;

    private static CallBack callBack = new CallBack() {
        @Override
        public void call(Object param) {

        }
    };

    public static void main(String[] args) {

        sendMessage("{\"_method\":\"security_getGetCardUserInfoAll\",\"_id\":3,\"args\":{\"userpin\":\"88888888\"}}", new CallBack() {
            @Override
            public void call(Object param) {
                LinkedHashMap data = JsonUtils.reader(param.toString(), LinkedHashMap.class);
                if ("security_getGetCardUserInfoAll".equals(data.get("_method"))) {
                    try {
                        login(((List) BeanUtil.getProperty(data, "_args.Data")).get(0).toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    public static void clearClient() {
        client = null;
        open = false;
    }


    public static void setClient(WebSocketClient client1) {
        client = client1;
    }

    public static void setOpen(boolean open1) {
        open = open1;
    }


    public static synchronized void sendMessage(String message, CallBack callBack1) {
        WebSocketClient client1 = openClient();
        callBack = callBack1;
        client1.send(message);
    }

    public static synchronized WebSocketClient openClient() {
        if (client != null) {
            return client;
        }
        try {

            URI uri = new URI("wss://wss.singlewindow.cn:61231/");

            WebSocketClient client1 = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {

                }

                @Override
                public void onMessage(String s) {
                    System.out.println(s);
                    LinkedHashMap data = JsonUtils.reader(s, LinkedHashMap.class);
                    if ("open".equals(data.get("_method"))) {
                        setOpen(true);
                    } else {
                        callBack.call(s);
                    }

                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    System.out.println("关闭连接" + s);
                }

                @Override
                public void onError(Exception e) {

                }
            };
            client1.connect();
            while (!open) {
                setClient(client1);
                Thread.currentThread().sleep(10L);
            }
            return client1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void login(String userInfo) throws Exception {


        String[] userInfos = userInfo.split("\\|\\|");
        // 创建一个Cookie存储对象
        final CookieStore cookieStore = new BasicCookieStore();

        // 创建HttpClientContext对象，并将Cookie存储对象设置进去
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        // 创建HttpClient对象
        HttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        // 创建HttpGet对象，用于发起HTTP GET请求
        HttpGet httpGet = new HttpGet("https://app.singlewindow.cn/cas/login?service=https%3A%2F%2Fwww.singlewindow.cn%2Fsw%2Flogin.swdo");

        // 执行请求，获取响应
        HttpResponse response = httpClient.execute(httpGet, context);

        // 从context中取出cookie
        //cookieStore = context.getCookieStore();

        // 遍历cookieStore中的所有cookie
        List<Cookie> cookies = cookieStore.getCookies();
        for (org.apache.http.cookie.Cookie cookie : cookies) {
            System.out.println("Cookie: " + cookie.getName() + " = " + cookie.getValue());
        }

        String responseStr = toString(response);
        Document doc = Jsoup.parse(responseStr);
        Element fm1 = doc.getElementById("fm1");
        Elements elements = fm1.getElementsByTag("input");
        Map<String, String> formData = new LinkedHashMap<>();
        for (Element input : elements) {
            String fieldName = input.attr("name");
            String fieldValue = input.attr("value");
            formData.put(fieldName, fieldValue);
            System.out.println("Field Name: " + fieldName + ", Field Value: " + fieldValue);
        }

        String key = doc.getElementById("user_sm_dt").text();
        System.out.println("加密密钥：" + key);
        formData.put("icCard", userInfos[5]);
        formData.put("certNo", userInfos[0]);
        formData.put("sgm", "1");
        formData.put("userPin", JSUtils.CaData_KXC("88888888", key));
        sendMessage("{\"_method\":\"security_SpcSignRandom\",\"_id\":2,\"args\":{\"passwd\":\"88888888\",\"random\":\"" + formData.get("random") + "\"}}", new CallBack() {
            @Override
            public void call(Object param) {
                try {
                    LinkedHashMap data = JsonUtils.reader(param.toString(), LinkedHashMap.class);
                    formData.put("signData", ((List) BeanUtil.getProperty(data, "_args.Data")).get(0).toString());


                    String loginUrl = "https://app.singlewindow.cn" + fm1.attr("action");
                    System.out.println("登录地址：" + loginUrl);
                    HttpPost login = new HttpPost(loginUrl);
                    login.setEntity(mapToParams(formData));
                    HttpResponse response1 = httpClient.execute(login, context);

                    //System.out.println(TestWs.toString(response1));
                    //System.out.println("=========================================================================");


                    List<Cookie> cookies1 = context.getCookieStore().getCookies();
                    for (org.apache.http.cookie.Cookie cookie : cookies1) {
                        System.out.println("Cookie: " + cookie.getName() + " = " + cookie.getValue());
                    }

                    System.out.println("登录参数：" + JsonUtils.toString(formData));
                    System.out.println(response1.getStatusLine().getStatusCode());

                    HttpGet home = new HttpGet("https://swapp.singlewindow.cn/deskserver/sw/deskIndex?menu_id=dec001&show_id=dec001th06leaf01");

                    HttpResponse response2 = httpClient.execute(home, context);

                    //System.out.println("=========================================================================");
                    //System.out.println(TestWs.toString(response2));
                    //System.out.println("=========================================================================");
                    List<Cookie> cookies2 = context.getCookieStore().getCookies();
                    for (org.apache.http.cookie.Cookie cookie : cookies2) {
                        System.out.println("Cookie: " + cookie.getName() + " = " + cookie.getValue());
                    }


                    //String url ="https://swapp.singlewindow.cn/decserver/sw/dec/merge/cusQuery?limit=10&offset=0&stName=updateTime&stOrder=desc&decStatusInfo=%25257B%252522cusCiqNoHidden%252522%3A%252522%252522%2C%252522dclTrnRelFlagHidden%252522%3A%252522%252522%2C%252522transPreNoHidden%252522%3A%252522%252522%2C%252522cusIEFlagHidden%252522%3A%252522%252522%2C%252522cusOrgCode%252522%3A%252522%252522%2C%252522dclTrnRelFlag%252522%3A%2525220%252522%2C%252522cusDecStatus%252522%3A%252522%252522%2C%252522etpsCategory%252522%3A%252522A%252522%2C%252522cusIEFlag%252522%3A%252522I%252522%2C%252522entryId%252522%3A%252522%252522%2C%252522cusCiqNo%252522%3A%252522%252522%2C%252522cnsnTradeCode%252522%3A%252522%252522%2C%252522billNo%252522%3A%252522%252522%2C%252522customMaster%252522%3A%252522%252522%2C%252522tableFlag%252522%3A%2525220%252522%2C%252522updateTime%252522%3A%2525222024-03-14%252522%2C%252522updateTimeEnd%252522%3A%2525222024-03-14%252522%2C%252522operateDate%252522%3A%2525221%252522%2C%252522verifyCode%252522%3A%252522%252522%2C%252522queryPage%252522%3A%252522cusBasicQuery%252522%2C%252522operType%252522%3A%2525220%252522%25257D&_=1710379529956";
                    String url = "https://swapp.singlewindow.cn/decserver/sw/dec/merge/cusQuery?limit=10&offset=0&stName=updateTime&stOrder=desc&decStatusInfo=%25257B%252522cusCiqNoHidden%252522%3A%252522%252522%2C%252522dclTrnRelFlagHidden%252522%3A%252522%252522%2C%252522transPreNoHidden%252522%3A%252522%252522%2C%252522cusIEFlagHidden%252522%3A%252522%252522%2C%252522cusOrgCode%252522%3A%252522%252522%2C%252522operType%252522%3A%2525220%252522%2C%252522dclTrnRelFlag%252522%3A%2525220%252522%2C%252522etpsCategory%252522%3A%252522A%252522%2C%252522cusIEFlag%252522%3A%252522E%252522%2C%252522cusTradeNationCode%252522%3A%252522%252522%2C%252522cusTradeNationCodeName%252522%3A%252522%252522%2C%252522orgCode%252522%3A%252522%252522%2C%252522orgCodeName%252522%3A%252522%252522%2C%252522cusCiqNo%252522%3A%252522%252522%2C%252522entryId%252522%3A%252522%252522%2C%252522cusDecStatus%252522%3A%25252210%252522%2C%252522updateTime%252522%3A%2525222023-09-19%252522%2C%252522updateTimeEnd%252522%3A%2525222024-03-19%252522%2C%252522operateDate%252522%3A%2525225%252522%2C%252522billNo%252522%3A%252522%252522%2C%252522isBillNoExactQuery%252522%3A%2525220%252522%2C%252522verifyCode%252522%3A%252522%252522%2C%252522queryPage%252522%3A%252522cusAdvancedQuery%252522%25257D&_=1710830841289";
                    HttpGet order = new HttpGet(url);
                    HttpResponse response3 = httpClient.execute(order, context);
                    System.out.println("=========================================================================");
                    String rowsStr = TestWs.toString(response3);
                    System.out.println(rowsStr);
                    LinkedHashMap rowBean = JsonUtils.reader(rowsStr, LinkedHashMap.class);

                    String totalStr = rowBean.get("total").toString();
                    if ("0".equals(totalStr)) {
                        System.out.println("为查询到报关单");
                    } else {
                        List<LinkedHashMap> rows = (List<LinkedHashMap>) rowBean.get("rows");

                        LinkedHashMap row = rows.get(0);

                        String cusCiqNo = (String) row.get("cusCiqNo");
                        String cusIEFlag = (String)row.get("cusIEFlag");
                        String encryptString = (String)row.get("encryptString");
                        String fromList = "1";
                        String operationType = "cusEdit";
                        Map<String, String> params = new HashMap<String, String>(){{
                            put("cusCiqNo", cusCiqNo);
                            put("cusIEFlag", cusIEFlag);
                            put("encryptString", encryptString);
                            put("fromList", fromList);
                            put("operationType", operationType);
                        }};

                        url = "https://swapp.singlewindow.cn/decserver/sw/dec/merge/ddt_7Nj8gC";
                        HttpPost inventory = new HttpPost(url);
                        inventory.addHeader("Content-Type", "application/json;charset=utf-8"); //添加请求头
                        //inventory.setEntity(new StringEntity(JsonUtils.toString(params), "utf-8"));
                        inventory.setEntity(new StringEntity("{\"cusCiqNo\":\""+ cusCiqNo +"\",\"cusIEFlag\":\""+ cusIEFlag +"\",\"encryptString\":\""+ encryptString +"\",\"fromList\":\""+ fromList +"\",\"operationType\":\""+ operationType +"\"}", "utf-8"));
                        HttpResponse response4 = httpClient.execute(inventory, context);
                        System.out.println("=========================================================================");
                        String queryResult = TestWs.toString(response4);
                        System.out.println("报关单详情：" + queryResult);
                        String s = JSUtils.loadAESDecryptStr(queryResult);
                        System.out.println(s);
                    }


                    /*HttpPost inventory = new HttpPost("https://swapp.singlewindow.cn/swceb2web/inventory/inventoryQuery");
                    inventory.addHeader("Content-Type", "application/json;charset=utf-8"); //添加请求头
                    inventory.setEntity(new StringEntity("{\n" +
                            "\t\"limit\": 50,\n" +
                            "\t\"offset\": 0,\n" +
                            "\t\"order\": \"asc\",\n" +
                            "\t\"queryArea\": \"QUERY\",\n" +
                            "\t\"formCondition\": \"{\\\"sysDateFrom\\\":\\\"2024-03-14 00:00:00\\\",\\\"sysDateTo\\\":\\\"2024-03-14 23:59:59\\\",\\\"appStatus\\\":\\\"0\\\",\\\"appStatusText\\\":\\\"全部\\\",\\\"tradeMode\\\":\\\"0\\\",\\\"tradeModeText\\\":\\\"全部\\\",\\\"collStatus\\\":\\\"0\\\",\\\"collStatusText\\\":\\\"全部\\\",\\\"taxInfoStatus\\\":\\\"0\\\",\\\"taxInfoStatusText\\\":\\\"全部\\\"}\"\n" +
                            "}","utf-8"));
                    HttpResponse response4 = httpClient.execute(inventory, context);
                    System.out.println("=========================================================================");
                    String queryResult = TestWs.toString(response4);
                    System.out.println(queryResult);
                    System.out.println(JSUtils.loadMenuTypeStr(queryResult));*/
                } catch (Exception e) {

                }
            }
        });


        // 然后你可以使用这些cookie信息配合htmlParser进行网页内容的爬取
    }


    public static UrlEncodedFormEntity mapToParams(Map<String, String> formData) throws Exception {
        List<NameValuePair> formParams = new ArrayList<>();
        for (String key : formData.keySet()) {
            formParams.add(new BasicNameValuePair(key, formData.get(key)));
        }

        formParams.add(new BasicNameValuePair("param2", "value2"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
        return entity;
    }


    private static String toString(HttpResponse response) {
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            return null;
        }
        try {
            String result = IoUtil.readUtf8(entity.getContent());
            return result;
        } catch (Exception e) {
            return null;
        }
    }
}
